package com.mapaower.admin.service;

import com.mapaower.admin.entity.Permission;
import com.mapaower.admin.entity.Role;
import com.mapaower.admin.repository.PermissionRepository;
import com.mapaower.admin.repository.RoleRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class RoleService {

    @Autowired
    private RoleRepository roleRepository;

    @Autowired
    private PermissionRepository permissionRepository;

    public Role getRoleById(Long id) {
        return roleRepository.findById(id).orElse(null);
    }

    public Role getRoleByName(String name) {
        return roleRepository.findByName(name).orElse(null);
    }

    public List<Role> getAllRoles() {
        return roleRepository.findAll();
    }

    @Transactional
    public Role createRole(Role role) {
        if (roleRepository.existsByName(role.getName())) {
            throw new RuntimeException("角色名称已存在");
        }

        // 保存角色（包括权限关联）
        return roleRepository.save(role);
    }

    @Transactional
    public Role updateRole(Long id, Role role) {
        Role existingRole = getRoleById(id);
        if (existingRole == null) {
            throw new RuntimeException("角色不存在");
        }

        // 更新角色名称
        if (role.getName() != null && !role.getName().equals(existingRole.getName())) {
            if (roleRepository.existsByName(role.getName())) {
                throw new RuntimeException("角色名称已存在");
            }
            existingRole.setName(role.getName());
        }

        // 更新角色描述
        if (role.getDescription() != null) {
            existingRole.setDescription(role.getDescription());
        }

        // 更新角色权限
        if (role.getPermissions() != null) {
            existingRole.setPermissions(role.getPermissions());
        }

        return roleRepository.save(existingRole);
    }

    @Transactional
    public boolean deleteRole(Long id) {
        // 检查角色是否存在
        if (!roleRepository.existsById(id)) {
            return false;
        }

        roleRepository.deleteById(id);
        return true;
    }

    @Transactional
    public Role addPermissionToRole(Long roleId, Long permissionId) {
        Role role = getRoleById(roleId);
        Permission permission = permissionRepository.findById(permissionId).orElse(null);

        if (role == null || permission == null) {
            throw new RuntimeException("角色或权限不存在");
        }

        // 添加权限到角色
        if (role.getPermissions() == null) {
            role.setPermissions(new HashSet<>());
        }
        role.getPermissions().add(permission);

        return roleRepository.save(role);
    }

    @Transactional
    public Role removePermissionFromRole(Long roleId, Long permissionId) {
        Role role = getRoleById(roleId);
        Permission permission = permissionRepository.findById(permissionId).orElse(null);

        if (role == null || permission == null) {
            throw new RuntimeException("角色或权限不存在");
        }

        // 从角色中移除权限
        if (role.getPermissions() != null) {
            role.getPermissions().remove(permission);
        }

        return roleRepository.save(role);
    }
}